<template>
  <view class="confirm-order-content">

    <view class="order-info">
      <view class="order-detail">
        <view class="detail-title">

          <text>订单详情</text>
        </view>
        <scroll-view class="detail-list" scroll-y="true" @touchmove.stop.prevent>
          <template v-for="(v,i) in cartMap.values()" :key="i">
            <view class="list-item">
              <image class="item-left" :src="v.product.img" mode="scaleToFill"></image>
              <view class="item-center">
                <text class="item-center-name">{{v.product.name}}</text>

              </view>
              <view class="item-right">
                <text class="item-right-price">{{displayPrice(v.product.price)}}</text>
                <text class="item-right-count">{{"x"+v.count}}</text>
              </view>
            </view>
          </template>
        </scroll-view>
        <view class="detail-coupon-content" @click="couponClick">
          <text>优惠券</text>
          <text v-if="couponList.length<=0">暂无优惠券 ></text>
          <text v-else style="color: red;">{{couponHint}} ></text>
        </view>
        <view class="detail-amount-info">
          <text>优惠价格</text>
          <text>{{`-${displayPrice(couponPrice)}`}}</text>
        </view>
      </view>

      <view class="pay-model">
        <view class="model-title">
          <text>支付方式</text>
        </view>
        <view class="model-weixin">
          <view class="weixin-selected">

            <uni-icons fontFamily="iconfont" :size="22" color="#00C800">{{`&#xe650;`}}</uni-icons>
            <text class="weixin-hint">微信支付</text>
          </view>
          <label>
            <checkbox :value="1" :checked="isCheckPay" />
          </label>

        </view>
      </view>

    </view>

    <view class="order-pay">
      <view :class="[topEmpty, isDisplayCoupon ?  topEmptyTrue: topEmptyFalse]">
        <view class="coupon-popup-content">
          <view class="popup-title">
            <text class="popup-title-hint">选择优惠券</text>
            <uni-icons type="closeempty" size="25" @click="couponClose"></uni-icons>
          </view>
          <scroll-view scroll-y="true" class="coupon-list" @touchmove.stop.prevent>
            <radio-group @change="radioChange">


              <template v-for="(item,index) in couponList " :key="index">
                <view class="coupon-list-item">
                  <view class="item-top">
                    <view class="item-top-left">
                      <!--                    <text>¥</text>
                    <text class="coupon-value">2</text> -->
                      <text class="coupon-value"
                        v-if="item.coupon.valueHint>0">{{displayPriceOrign(item.coupon.valueHint)}}</text>
                      <text class="discount-value"
                        v-if="item.coupon.discountValueHint.length>0">{{item.coupon.discountValueHint}}</text>

                    </view>
                    <view class="item-top-center">
                      <text>{{item.coupon.limitHint}}</text>
                      <text>{{`${processAt(item.coupon.coupon_batch.valided_at)}-${processAt(item.coupon.coupon_batch.expired_at)}`}}</text>
                    </view>
                    <label class="item-top-right">
                      <radio :value="index" :checked="index == selectIndex" />
                    </label>
                  </view>
                  <view class="item-bottom">
                    <uni-collapse>
                      <custom-collapse-item title="使用说明" title-border="none">
                        <view class="coupon-explain-value">
                          <text>{{item.coupon.coupon_batch.remark}}</text>
                        </view>
                      </custom-collapse-item>
                    </uni-collapse>
                  </view>


                </view>
              </template>
            </radio-group>
          </scroll-view>
        </view>
      </view>
      <view class="pay-content">

        <view class="pay-info">
          <text>待支付</text>
          <text class="pay-value">{{displayPrice(totalPrice)}}</text>
        </view>
        <text class="pay-bt" @click="clickPay">支付</text>
      </view>
    </view>

  </view>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import { onReady, onLoad, onBackPress } from '@dcloudio/uni-app';
  import { createOrder, updateOrderState, getPayInfo, queryUserAllCoupon } from "@/common/utils/requestModel.js"
  import { displayPrice, loadingShow, loadingHide, showToast, displayPriceOrign } from "@/common/utils/public.ts"

  import { CartProduct, CreateOrderBean, CreateOrderItem, CouponBean, Coupon, CouponBatch, CouponTicket } from '@/common/models/BaseData.ts'
  import { RaycastHit } from 'XrFrame/xrFrameSystem';

  onLoad(() => {

  })
  onReady(() => {
    console.log('onReady--')
    initData()

  })

  onBackPress(() => {
    console.log('onBackPress--')

  })



  const isDisplayCoupon = ref(false)
  const isCheckPay = ref(true)

  const topEmpty = "top-empty"
  const topEmptyFalse = "top-empty-false"
  const topEmptyTrue = "top-empty-true"

  const cartMap = ref(new Map<string, CartProduct>());
  const totalPrice = ref(0)
  let orignTotal = 0

  function initData() {
    let app = getApp()
    let total = 0
    app.globalData.cartMap.forEach((value, key) => {
      cartMap.value.set(key, value);
      total += (value.product.price * value.count)
    });
    totalPrice.value = total
    orignTotal = total
    console.log("购买商品信息:", cartMap.value)
    checkCoupon()
  }


  function requestCreateOrder() {
    loadingShow("生成中..")
    let items = new Array<CreateOrderItem>()
    cartMap.value.forEach((value, key) => {
      items.push(new CreateOrderItem(value.product.id, value.count))
    });
    let deviceId = getApp().globalData.deviceInfo.object_id
    let couponId = 0
    if (select != null || select != undefined) {
      couponId = select.coupon.coupon_ticket.object_id
    }

    let order = new CreateOrderBean(deviceId, couponId, items)
    const json = JSON.stringify(order);
    console.log("创建订单信息:", json)

    loadingShow("处理中")
    createOrder(json).then(result => {
      console.log("创建订单信息:", result)
      if (result.data.code != undefined) {
        loadingHide(false, "失败，请重新购买")
        return
      }


      let newOrder = {
        object_id: result.data.object_id,
        real_price: result.data.real_price
      }


      getApp().globalData.createOrder = { id: newOrder.object_id }
      console.log("创建订单信息---赋值:", newOrder)
      if (result.data.real_price <= 0) {
        console.log('创建订单支付成功success:');
        uni.reLaunch({
          url: '/sub_buy_flow_pages/order_list'
        });
        return
      }
      getPayInfo(newOrder.object_id).then(result => {
        console.log("支付信息结果:", result)
        if (result.data.code != undefined) {
          loadingHide(false, "支付失败")
          return
        }

        let d = result.data
        loadingHide(true)
        /*      let parmas = {
                appid: d.appId,
                noncestr: d.nonceStr,
                // orderId: d.orderId,
                package: d.package,
                paydeviceid: d.payDeviceId,
                payid: d.payId,
                paysign: d.paySign,
                prepayid: d.prepayId,
                signtype: d.signType,
                timestamp: `${d.timeStamp}`
              } */

        let p = {
          // appId: d.appId,
          nonceStr: d.nonceStr,
          package: d.package,
          paySign: d.paySign,
          signType: d.signType,
          timeStamp: `${d.timeStamp}`
        }
        console.log("支付信息：", p)
        uni.requestPayment({
          provider: 'wxpay',
          ...p,
          // ...result.data,
          success: function (res) {
            console.log('支付成功success:' + JSON.stringify(res));
            uni.reLaunch({
              url: '/sub_buy_flow_pages/order_list'
            });
          },
          fail: function (err) {
            console.log('支付失败fail:' + JSON.stringify(err));
            // loadingHide(false, "支付失败")
          }
        })
      }).catch(e => {
        loadingHide(false, "支付异常")
      })
    }).catch(e => {
      loadingHide(false, "数据异常")
    })
  }

  function couponClick() {
    console.log("点击显示优惠券")
    if (couponList.value.length > 0) {
      select = null
      couponHint.value = "使用优惠券"
      isDisplayCoupon.value = !isDisplayCoupon.value
    }
  }

  function couponClose() {
    isDisplayCoupon.value = false
    console.log("点击关闭优惠券", couponList)
    selectIndex = -1
    if (select == null) {
      couponPrice.value = 0
      totalPrice.value = orignTotal
    }
  }


  class DisplayCoupon {
    coupon : CouponBean
    isChecked : boolean = false
    constructor(cb : CouponBean) {
      this.coupon = cb
    }
  }

  let couponHint = ref("使用优惠券")

  const couponList = ref<Array<DisplayCoupon>>([])

  async function checkCoupon() {
    let d = uni.getStorageSync(getApp().globalData.DEVICE_TAG)
    let items = new Array<String>()
    cartMap.value.forEach((value, key) => {
      items.push(value.product.id)
    });
    let pString = items.join(",")
    queryUserAllCoupon(d.owner_id, {
      products: pString,
      devices: d.object_id
    }).then((result => {
      console.log("优惠券所有信息:", result)
      if (result.data.code != undefined || result.data.items.length <= 0) {
        console.log("优惠券异常或无:")
        return
      }

      let arr = new Array<DisplayCoupon>()
      for (const item of result.data.items) {
        let coupon = new Coupon(
          item.coupon.coupon_batch_id,
          item.coupon.object_id,
          item.coupon.mode,
          item.coupon.threshold,
          item.coupon.reduce,
          item.coupon.discount,
          item.coupon.quantity,
          item.coupon.got,
          item.coupon.used
        )
        let coupon_batch = new CouponBatch(
          item.coupon_batch.operator_id,
          item.coupon_batch.coupon_type,
          item.coupon_batch.batch,
          item.coupon_batch.name,
          item.coupon_batch.quantity,
          item.coupon_batch.got,
          item.coupon_batch.used,
          item.coupon_batch.valided_at,
          item.coupon_batch.expired_at,
          item.coupon_batch.remark
        )
        let coupon_ticket = new CouponTicket(
          item.coupon_ticket.code,
          item.coupon_ticket.coupon_id,
          item.coupon_ticket.created_at,
          item.coupon_ticket.deleted,
          item.coupon_ticket.device_id,
          item.coupon_ticket.object_id,
          item.coupon_ticket.order_id,
          item.coupon_ticket.updated_at,
          item.coupon_ticket.user_id
        )

        arr.push(
          new DisplayCoupon(
            new CouponBean(coupon, coupon_batch, coupon_ticket)
          )
        )

      }

      couponList.value = arr
      radioChange({ detail: ref(0) })
    })).catch((e) => {

    })
  }

  let select : DisplayCoupon = null
  let selectIndex = -1

  function radioChange(evt) {
    selectIndex = evt.detail.value
    let coupon = couponList.value[evt.detail.value]
    select = coupon

    console.log("选中的优惠券", coupon)
    couponHint.value = select.coupon.limitHint
    processCouponPrice()
    isDisplayCoupon.value = false
  }

  let couponPrice = ref(0)
  function processCouponPrice() {

    let cp = select.coupon
    if (totalPrice.value >= cp.coupon.threshold) {
      let amount = 0
      if (cp.coupon.reduce > 0 && cp.coupon.discount > 0) {
        amount = ((totalPrice.value - cp.coupon.reduce) * cp.coupon.discount) / 100
      } else if (cp.coupon.discount > 0) {
        amount = (totalPrice.value * cp.coupon.discount) / 100
      } else if (cp.coupon.reduce > 0) {
        amount = totalPrice.value - cp.coupon.reduce
      } else {
        amount = totalPrice.value
      }
      couponPrice.value = (totalPrice.value - amount)
      totalPrice.value = amount
    }
  }


  function clickPay() {

    console.log("点击支付", isCheckPay)
    if (!isCheckPay.value) {
      showToast("请购选微信支付")
      return
    }
    requestCreateOrder()
    // if (newOrder.object_id.length <= 0 || newOrder.real_price <= 0) {

    //   showToast("数据异常，请重新购买")
    //   return
    // }


  }

  function processAt(date : string) : string {
    let list = date.split(" ")
    return list[0]
  }
</script>

<style lang="scss">
  .confirm-order-content {
    position: relative;
    display: block;
    width: 100%;
    // height: 100%;
    padding-top: 20rpx;
    padding-bottom: 130rpx;
    // box-sizing: border-box;
  }

  .order-info {
    width: 100%;
    padding: 10rpx 20rpx;
    box-sizing: border-box;


    .order-detail {
      width: 100%;
      height: 600rpx;
      background: $color-white;
      border-radius: 20rpx;
      padding: 20rpx;
      box-sizing: border-box;

      .detail-title {
        width: 100%;
        padding: 10rpx 0;
        font-weight: 700;
      }

      .detail-list {
        width: 100%;
        height: 320rpx;
        padding: 10px 0;
        box-sizing: border-box;

        .list-item {
          display: flex;
          flex-direction: row;
          width: 100%;
          height: 135rpx;
          // margin-top: 20rpx;

          .item-left {
            width: 140rpx;
            height: 100%;
          }

          .item-center {
            display: flex;
            flex-direction: column;
            justify-content: center;
            width: 50%;
            padding: 10rpx 10rpx;
            // background: #D8D8D8;

            .item-center-name {
              font-size: 30rpx;
            }

            .item-center-price {
              font-size: 30rpx;
            }

          }

          .item-right {
            display: flex;
            flex-direction: column;
            align-items: flex-end;
            width: 30%;
            color: #5C5C5C;

            // background: #4fd85f;
            .item-right-price {
              font-size: 35rpx;
            }

            .item-right-count {
              font-size: 30rpx;
            }
          }
        }

      }

      .detail-coupon-content {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        height: 90rpx;
        border-bottom: 1rpx solid $color-E6E6E6;

        text:nth-child(2) {
          font-size: 30rpx;
          color: #696969;
        }
      }

      .detail-amount-info {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        height: 90rpx;

        text:nth-child(2) {
          color: #E62129;
        }
      }

    }

    .pay-model {
      display: flex;
      flex-direction: column;
      justify-content: center;
      width: 100%;
      padding: 20rpx;
      margin-top: 20rpx;
      border-radius: 20rpx;
      box-sizing: border-box;
      background: $color-white;

      .model-title {
        width: 100%;
        padding: 20rpx 0;
        font-weight: 700;
        border-bottom: 1px solid #D8D8D8;
      }

      .model-weixin {
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 80rpx;

        .weixin-selected {
          display: flex;
          flex-direction: row;
          align-items: center;
          height: 100%;
          padding-top: 10rpx;
          box-sizing: border-box;

          .weixin-hint {
            margin-bottom: 10rpx;
          }
        }
      }

    }
  }



  .order-pay {
    position: fixed;
    bottom: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;

    .top-empty {

      width: 100%;
      height: 100%;
      background: rgba(0, 0, 0, 0.3);
      touch-action: none;
      pointer-events: auto;
    }

    .top-empty-false {
      display: none;
    }

    .top-empty-true {
      display: block;
    }

    .coupon-popup-content {
      position: absolute;
      bottom: 0;
      // visibility: hidden;
      width: 100%;
      height: 700rpx;
      border-radius: 20rpx 20rpx 0 0;
      border-bottom: 1rpx solid black;
      margin-bottom: 130rpx;
      background: #e3e3e3;
      z-index: 1;
      touch-action: none;
      pointer-events: auto;

      .popup-title {
        position: relative;
        display: flex;
        flex-direction: row;
        justify-content: space-between;
        width: 100%;
        line-height: 100rpx;
        padding: 0 20rpx;
        box-sizing: border-box;
        background: $color-white;
        border-radius: 20rpx 20rpx 0 0;

        .popup-title-hint {
          width: 100%;
          text-align: center;
          line-height: 100rpx;
          font-size: 35rpx;
          font-weight: 700;
        }

        text:nth-child(2) {
          position: absolute;
          right: 0;
        }
      }

      .coupon-list {
        width: 100%;
        height: 600rpx;
        padding: 20rpx;
        box-sizing: border-box;

        .coupon-list-item {
          width: 100%;
          height: 270rpx;

          .item-top {
            display: inline-flex;
            width: 100%;
            height: 65%;
            border-radius: 20rpx;
            background: $color-white;
            border-bottom: 1px solid #D8D8D8;

            .item-top-left {
              width: 30%;
              height: 100%;
              line-height: 160rpx;
              text-align: center;
              color: red;

              .coupon-value {
                font-size: 50rpx;
                font-weight: 700;
              }

              .coupon-value::first-letter {
                font-size: 50%;
                /* 将第一个字母的字体大小设为原来的50% */
              }

              .discount-value {
                font-size: 24px;
                display: inline-block;
                position: relative;
              }

              .discount-value::after {
                content: "2";
                position: absolute;
                top: 0;
                left: 100%;
                /* 使伪元素出现在主内容之后 */
                transform: scale(0.7) translateX(-50%);
                /* 缩小并调整位置 */
                transform-origin: left;
                /* 调整缩放的基点 */
              }


              // .coupon-value {
              //   font-size: 80rpx;
              //   font-weight: 700;

              // }
            }

            .item-top-center {
              display: flex;
              flex-direction: column;
              justify-content: center;
              width: 50%;
              height: 100%;

              text:nth-child(1) {
                padding: 10rpx 0;
                font-weight: 700;
              }

              text:nth-child(2) {
                padding: 10rpx 0;
                font-size: 30rpx;
              }
            }

            .item-top-right {
              width: 20%;
              height: 100%;
              line-height: 160rpx;
              text-align: center;
            }

          }

          .item-bottom {
            width: 100%;
            height: 35%;
            padding: 10rpx 0;
            border-radius: 20rpx;
            background: $color-white;

            .coupon-explain-value {
              width: 100%;
              padding: 10rpx 30rpx;
              box-sizing: border-box;
              text-align: left;
            }

          }

        }
      }

    }


    // font-size: 40rpx;
    .pay-content {
      position: absolute;
      bottom: 0;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      width: 100%;
      height: 130rpx;
      background: #ffffff;
      color: #111111;
      pointer-events: auto;

      .pay-info {
        text:nth-child(1) {
          margin-left: 20rpx;
        }

        .pay-value {
          margin-left: 20rpx;
          color: #E62129;

        }
      }


      .pay-bt {
        width: 180rpx;
        height: 70rpx;
        line-height: 70rpx;
        margin-right: 20rpx;
        text-align: center;
        border-radius: 35rpx;
        background: #FFD804;
      }
    }
  }
</style>